<!DOCTYPE html>
<html>
  <head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
  <meta name="description" content="刘清政">
  <meta name="keyword" content="hexo-theme">
  
    <link rel="shortcut icon" href="/css/images/logo.png">
  
  <title>
    
      python/Django-rest-framework框架/7-drf-过滤排序分页异常处理 | Justin-刘清政的博客
    
  </title>
  <link href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <link href="//cdnjs.cloudflare.com/ajax/libs/nprogress/0.2.0/nprogress.min.css" rel="stylesheet">
  <link href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/tomorrow.min.css" rel="stylesheet">
  
<link rel="stylesheet" href="/css/style.css">

  
    
<link rel="stylesheet" href="/css/plugins/gitment.css">

  
  <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/geopattern/1.2.3/js/geopattern.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/nprogress/0.2.0/nprogress.min.js"></script>
  
    
<script src="/js/qrious.js"></script>

  
  
    
<script src="/js/gitment.js"></script>

  
  

  
<meta name="generator" content="Hexo 4.2.0"></head>
<div class="wechat-share">
  <img src="/css/images/logo.png" />
</div>

  <body>
    <header class="header fixed-header">
  <div class="header-container">
    <a class="home-link" href="/">
      <div class="logo"></div>
      <span>Justin-刘清政的博客</span>
    </a>
    <ul class="right-list">
      
        <li class="list-item">
          
            <a href="/" class="item-link">主页</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/tags/" class="item-link">标签</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/archives/" class="item-link">归档</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/about/" class="item-link">关于我</a>
          
        </li>
      
    </ul>
    <div class="menu">
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </div>
    <div class="menu-mask">
      <ul class="menu-list">
        
          <li class="menu-item">
            
              <a href="/" class="menu-link">主页</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/tags/" class="menu-link">标签</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/archives/" class="menu-link">归档</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/about/" class="menu-link">关于我</a>
            
          </li>
        
      </ul>
    </div>
  </div>
</header>

    <div id="article-banner">
  <h2>python/Django-rest-framework框架/7-drf-过滤排序分页异常处理</h2>



  <p class="post-date">2020-06-28</p>
    <!-- 不蒜子统计 -->
    <span id="busuanzi_container_page_pv" style='display:none' class="">
        <i class="icon-smile icon"></i> 阅读数：<span id="busuanzi_value_page_pv"></span>次
    </span>
  <div class="arrow-down">
    <a href="javascript:;"></a>
  </div>
</div>
<main class="app-body flex-box">
  <!-- Article START -->
  <article class="post-article">
    <section class="markdown-content"><h1 id="一-过滤Filtering"><a href="#一-过滤Filtering" class="headerlink" title="一 过滤Filtering"></a>一 过滤Filtering</h1><p>对于列表数据可能需要根据字段进行过滤，我们可以通过添加django-fitlter扩展来增强支持。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">pip install django-filter</span><br></pre></td></tr></table></figure>

<p>在配置文件中增加过滤后端的设置：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">INSTALLED_APPS = [</span><br><span class="line">    ...</span><br><span class="line">    <span class="string">'django_filters'</span>,  <span class="comment"># 需要注册应用，</span></span><br><span class="line">]</span><br><span class="line"></span><br><span class="line">REST_FRAMEWORK = &#123;</span><br><span class="line">    ...</span><br><span class="line">    <span class="string">'DEFAULT_FILTER_BACKENDS'</span>: (<span class="string">'django_filters.rest_framework.DjangoFilterBackend'</span>,)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在视图中添加filter_fields属性，指定可以过滤的字段</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">StudentListView</span><span class="params">(ListAPIView)</span>:</span></span><br><span class="line">    queryset = Student.objects.all()</span><br><span class="line">    serializer_class = StudentSerializer</span><br><span class="line">    filter_fields = (<span class="string">'age'</span>, <span class="string">'sex'</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 127.0.0.1:8000/four/students/?sex=1</span></span><br></pre></td></tr></table></figure>

<h1 id="二-排序"><a href="#二-排序" class="headerlink" title="二 排序"></a>二 排序</h1><p>对于列表数据，REST framework提供了<strong>OrderingFilter</strong>过滤器来帮助我们快速指明数据按照指定字段进行排序。</p>
<p>使用方法：</p>
<p>在类视图中设置filter_backends，使用<code>rest_framework.filters.OrderingFilter</code>过滤器，REST framework会在请求的查询字符串参数中检查是否包含了ordering参数，如果包含了ordering参数，则按照ordering参数指明的排序字段对数据集进行排序。</p>
<p>前端可以传递的ordering参数的可选字段值需要在ordering_fields中指明。</p>
<p>示例：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">StudentListView</span><span class="params">(ListAPIView)</span>:</span></span><br><span class="line">    queryset = Student.objects.all()</span><br><span class="line">    serializer_class = StudentModelSerializer</span><br><span class="line">    filter_backends = [OrderingFilter]</span><br><span class="line">    ordering_fields = (<span class="string">'id'</span>, <span class="string">'age'</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 127.0.0.1:8000/books/?ordering=-age</span></span><br><span class="line"><span class="comment"># -id 表示针对id字段进行倒序排序</span></span><br><span class="line"><span class="comment"># id  表示针对id字段进行升序排序</span></span><br></pre></td></tr></table></figure>



<p>如果需要在过滤以后再次进行排序，则需要两者结合!</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> rest_framework.generics <span class="keyword">import</span> ListAPIView</span><br><span class="line"><span class="keyword">from</span> students.models <span class="keyword">import</span> Student</span><br><span class="line"><span class="keyword">from</span> .serializers <span class="keyword">import</span> StudentModelSerializer</span><br><span class="line"><span class="keyword">from</span> django_filters.rest_framework <span class="keyword">import</span> DjangoFilterBackend</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Student3ListView</span><span class="params">(ListAPIView)</span>:</span></span><br><span class="line">    queryset = Student.objects.all()</span><br><span class="line">    serializer_class = StudentModelSerializer</span><br><span class="line">    filter_fields = (<span class="string">'age'</span>, <span class="string">'sex'</span>)</span><br><span class="line">    <span class="comment"># 因为局部配置会覆盖全局配置,所以需要重新把过滤组件核心类再次声明,</span></span><br><span class="line">    <span class="comment"># 否则过滤功能会失效</span></span><br><span class="line">    filter_backends = [OrderingFilter,DjangoFilterBackend]</span><br><span class="line">    ordering_fields = (<span class="string">'id'</span>, <span class="string">'age'</span>)</span><br></pre></td></tr></table></figure>

<h1 id="三-分页Pagination"><a href="#三-分页Pagination" class="headerlink" title="三 分页Pagination"></a>三 分页Pagination</h1><p>REST framework提供了分页的支持。</p>
<p>我们可以在配置文件中设置全局的分页方式，如：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">REST_FRAMEWORK = &#123;</span><br><span class="line">    <span class="string">'DEFAULT_PAGINATION_CLASS'</span>:  <span class="string">'rest_framework.pagination.PageNumberPagination'</span>,</span><br><span class="line">    <span class="string">'PAGE_SIZE'</span>: <span class="number">100</span>  <span class="comment"># 每页数目</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>也可通过自定义Pagination类，来为视图添加不同分页行为。在视图中通过<code>pagination_clas</code>属性来指明。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">LargeResultsSetPagination</span><span class="params">(PageNumberPagination)</span>:</span></span><br><span class="line">    page_size = <span class="number">1000</span></span><br><span class="line">    page_size_query_param = <span class="string">'page_size'</span></span><br><span class="line">    max_page_size = <span class="number">10000</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">BookDetailView</span><span class="params">(RetrieveAPIView)</span>:</span></span><br><span class="line">    queryset = BookInfo.objects.all()</span><br><span class="line">    serializer_class = BookInfoSerializer</span><br><span class="line">    pagination_class = LargeResultsSetPagination</span><br></pre></td></tr></table></figure>

<p><strong>注意：如果在视图内关闭分页功能，只需在视图内设置</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">pagination_class = <span class="literal">None</span></span><br></pre></td></tr></table></figure>

<h2 id="可选分页器"><a href="#可选分页器" class="headerlink" title="可选分页器"></a>可选分页器</h2><p>1） <strong>PageNumberPagination</strong></p>
<p>前端访问网址形式：</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">GET  http://127.0.0.1:8000/students/?page=4</span><br></pre></td></tr></table></figure>

<p>可以在子类中定义的属性：</p>
<ul>
<li>page_size 每页数目</li>
<li>page_query_param 前端发送的页数关键字名，默认为”page”</li>
<li>page_size_query_param 前端发送的每页数目关键字名，默认为None</li>
<li>max_page_size 前端最多能设置的每页数量</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># APIView</span></span><br><span class="line"><span class="keyword">from</span> rest_framework.pagination <span class="keyword">import</span> PageNumberPagination</span><br><span class="line"><span class="comment"># 一 基本使用：url=url=http://127.0.0.1:8000/pager/?page=2&amp;size=3，size无效</span></span><br><span class="line"><span class="class"><span class="keyword">class</span>  <span class="title">Pager</span><span class="params">(APIView)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">get</span><span class="params">(self,request,*args,**kwargs)</span>:</span></span><br><span class="line">        <span class="comment"># 获取所有数据</span></span><br><span class="line">        ret=models.Book.objects.all()</span><br><span class="line">        <span class="comment"># 创建分页对象</span></span><br><span class="line">        page=PageNumberPagination()</span><br><span class="line">        <span class="comment"># 在数据库中获取分页的数据</span></span><br><span class="line">        page_list=page.paginate_queryset(ret,request,view=self)</span><br><span class="line">        <span class="comment"># 对分页进行序列化</span></span><br><span class="line">        ser=BookSerializer1(instance=page_list,many=<span class="literal">True</span>)</span><br><span class="line">        <span class="keyword">return</span> Response(ser.data)</span><br><span class="line"><span class="comment"># 二 自定制 url=http://127.0.0.1:8000/pager/?page=2&amp;size=3</span></span><br><span class="line"><span class="comment"># size=30，无效，最多5条</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Mypage</span><span class="params">(PageNumberPagination)</span>:</span></span><br><span class="line">    page_size = <span class="number">2</span></span><br><span class="line">    page_query_param = <span class="string">'page'</span></span><br><span class="line">    <span class="comment"># 定制传参</span></span><br><span class="line">    page_size_query_param = <span class="string">'size'</span></span><br><span class="line">    <span class="comment"># 最大一页的数据</span></span><br><span class="line">    max_page_size = <span class="number">5</span></span><br><span class="line"><span class="class"><span class="keyword">class</span>  <span class="title">Pager</span><span class="params">(APIView)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">get</span><span class="params">(self,request,*args,**kwargs)</span>:</span></span><br><span class="line">        <span class="comment"># 获取所有数据</span></span><br><span class="line">        ret=models.Book.objects.all()</span><br><span class="line">        <span class="comment"># 创建分页对象</span></span><br><span class="line">        page=Mypage()</span><br><span class="line">        <span class="comment"># 在数据库中获取分页的数据</span></span><br><span class="line">        page_list=page.paginate_queryset(ret,request,view=self)</span><br><span class="line">        <span class="comment"># 对分页进行序列化</span></span><br><span class="line">        ser=BookSerializer1(instance=page_list,many=<span class="literal">True</span>)</span><br><span class="line">        <span class="comment"># return Response(ser.data)</span></span><br><span class="line">        <span class="comment"># 这个也是返回Response对象，但是比基本的多了上一页，下一页，和总数据条数（了解即可）</span></span><br><span class="line">        <span class="keyword">return</span> page.get_paginated_response(ser.data)</span><br><span class="line">      </span><br><span class="line"><span class="comment">#ListAPIView</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 声明分页的配置类</span></span><br><span class="line"><span class="keyword">from</span> rest_framework.pagination <span class="keyword">import</span> PageNumberPagination</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">StandardPageNumberPagination</span><span class="params">(PageNumberPagination)</span>:</span></span><br><span class="line">    <span class="comment"># 默认每一页显示的数据量</span></span><br><span class="line">    page_size = <span class="number">2</span></span><br><span class="line">    <span class="comment"># 允许客户端通过get参数来控制每一页的数据量</span></span><br><span class="line">    page_size_query_param = <span class="string">"size"</span></span><br><span class="line">    max_page_size = <span class="number">10</span></span><br><span class="line">    <span class="comment"># 自定义页码的参数名</span></span><br><span class="line">    page_query_param = <span class="string">"p"</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">StudentAPIView</span><span class="params">(ListAPIView)</span>:</span></span><br><span class="line">    queryset = Student.objects.all()</span><br><span class="line">    serializer_class = StudentModelSerializer</span><br><span class="line">    pagination_class = StandardPageNumberPagination</span><br><span class="line"></span><br><span class="line"><span class="comment"># 127.0.0.1/four/students/?p=1&amp;size=5</span></span><br></pre></td></tr></table></figure>

<p>2）<strong>LimitOffsetPagination</strong></p>
<p>前端访问网址形式：</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">GET http://127.0.0.1/four/students/?limit=100&amp;offset=400</span><br></pre></td></tr></table></figure>

<p>可以在子类中定义的属性：</p>
<ul>
<li>default_limit 默认限制，默认值与<code>PAGE_SIZE</code>设置一直</li>
<li>limit_query_param limit参数名，默认’limit’</li>
<li>offset_query_param offset参数名，默认’offset’</li>
<li>max_limit 最大limit限制，默认None</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># APIView</span></span><br><span class="line"><span class="comment"># http://127.0.0.1:8000/pager/?offset=4&amp;limit=3</span></span><br><span class="line"><span class="keyword">from</span> rest_framework.pagination <span class="keyword">import</span> LimitOffsetPagination</span><br><span class="line"><span class="comment"># 也可以自定制，同简单分页</span></span><br><span class="line"><span class="class"><span class="keyword">class</span>  <span class="title">Pager</span><span class="params">(APIView)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">get</span><span class="params">(self,request,*args,**kwargs)</span>:</span></span><br><span class="line">        <span class="comment"># 获取所有数据</span></span><br><span class="line">        ret=models.Book.objects.all()</span><br><span class="line">        <span class="comment"># 创建分页对象</span></span><br><span class="line">        page=LimitOffsetPagination()</span><br><span class="line">        <span class="comment"># 在数据库中获取分页的数据</span></span><br><span class="line">        page_list=page.paginate_queryset(ret,request,view=self)</span><br><span class="line">        <span class="comment"># 对分页进行序列化</span></span><br><span class="line">        ser=BookSerializer1(instance=page_list,many=<span class="literal">True</span>)</span><br><span class="line">        <span class="comment"># return page.get_paginated_response(ser.data)</span></span><br><span class="line">        <span class="keyword">return</span> Response(ser.data)</span><br><span class="line"><span class="comment">#ListAPIView</span></span><br><span class="line"><span class="keyword">from</span> rest_framework.pagination <span class="keyword">import</span> LimitOffsetPagination</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">StandardLimitOffsetPagination</span><span class="params">(LimitOffsetPagination)</span>:</span></span><br><span class="line">    <span class="comment"># 默认每一页查询的数据量,类似上面的page_size</span></span><br><span class="line">    default_limit = <span class="number">2</span></span><br><span class="line">    limit_query_param = <span class="string">"size"</span></span><br><span class="line">    offset_query_param = <span class="string">"start"</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">StudentAPIView</span><span class="params">(ListAPIView)</span>:</span></span><br><span class="line">    queryset = Student.objects.all()</span><br><span class="line">    serializer_class = StudentModelSerializer</span><br><span class="line">    <span class="comment"># 调用页码分页类</span></span><br><span class="line">    <span class="comment"># pagination_class = StandardPageNumberPagination</span></span><br><span class="line">    <span class="comment"># 调用查询偏移分页类</span></span><br><span class="line">    pagination_class = StandardLimitOffsetPagination</span><br></pre></td></tr></table></figure>

<p>3）<strong>CursorPagination</strong></p>
<p>前端访问网址形式：</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">GET http://127.0.0.1/four/students/?cursor=cD0xNQ%3D%3D</span><br></pre></td></tr></table></figure>

<p>可以在子类中定义的属性：</p>
<ul>
<li>cursor_query_param:默认查询字段，不需要修改</li>
<li>page_size：每页数目</li>
<li>ordering：按什么排序，需要指定</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#APIView</span></span><br><span class="line"><span class="keyword">from</span> rest_framework.pagination <span class="keyword">import</span> CursorPagination</span><br><span class="line"><span class="comment"># 看源码，是通过sql查询，大于id和小于id</span></span><br><span class="line"><span class="class"><span class="keyword">class</span>  <span class="title">Pager</span><span class="params">(APIView)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">get</span><span class="params">(self,request,*args,**kwargs)</span>:</span></span><br><span class="line">        <span class="comment"># 获取所有数据</span></span><br><span class="line">        ret=models.Book.objects.all()</span><br><span class="line">        <span class="comment"># 创建分页对象</span></span><br><span class="line">        page=CursorPagination()</span><br><span class="line">        page.ordering=<span class="string">'nid'</span></span><br><span class="line">        <span class="comment"># 在数据库中获取分页的数据</span></span><br><span class="line">        page_list=page.paginate_queryset(ret,request,view=self)</span><br><span class="line">        <span class="comment"># 对分页进行序列化</span></span><br><span class="line">        ser=BookSerializer1(instance=page_list,many=<span class="literal">True</span>)</span><br><span class="line">        <span class="comment"># 可以避免页码被猜到</span></span><br><span class="line">        <span class="keyword">return</span> page.get_paginated_response(ser.data)</span><br><span class="line"><span class="comment"># ListAPIView</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyCursorPagination</span><span class="params">(CursorPagination)</span>:</span></span><br><span class="line">    page_size=<span class="number">2</span></span><br><span class="line">    ordering=<span class="string">'-id'</span></span><br><span class="line"><span class="keyword">from</span> rest_framework.generics <span class="keyword">import</span> ListAPIView</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">AuthorListView</span><span class="params">(ListAPIView)</span>:</span></span><br><span class="line">    serializer_class = serializers.AuthorModelSerializer</span><br><span class="line">    queryset = models.Author.objects.filter(is_delete=<span class="literal">False</span>)</span><br><span class="line">    pagination_class =MyCursorPagination</span><br></pre></td></tr></table></figure>



<h2 id="应用"><a href="#应用" class="headerlink" title="应用"></a>应用</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> rest_framework.pagination <span class="keyword">import</span> PageNumberPagination,LimitOffsetPagination,CursorPagination</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyPageNumberPagination</span><span class="params">(PageNumberPagination)</span>:</span></span><br><span class="line">    page_size = <span class="number">2</span></span><br><span class="line">    page_query_param = <span class="string">'page'</span></span><br><span class="line">    <span class="comment"># 定制传参</span></span><br><span class="line">    page_size_query_param = <span class="string">'size'</span></span><br><span class="line">    <span class="comment"># 最大一页的数据</span></span><br><span class="line">    max_page_size = <span class="number">5</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyLimitOffsetPagination</span><span class="params">(LimitOffsetPagination)</span>:</span></span><br><span class="line">    default_limit = <span class="number">2</span></span><br><span class="line">    <span class="comment"># 最大一页的数据</span></span><br><span class="line">    max_limit = <span class="number">5</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyCursorPagination</span><span class="params">(CursorPagination)</span>:</span></span><br><span class="line">    page_size=<span class="number">2</span></span><br><span class="line">    ordering=<span class="string">'-id'</span></span><br><span class="line"><span class="keyword">from</span> rest_framework.generics <span class="keyword">import</span> ListAPIView</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">AuthorListView</span><span class="params">(ListAPIView)</span>:</span></span><br><span class="line">    serializer_class = serializers.AuthorModelSerializer</span><br><span class="line">    queryset = models.Author.objects.filter(is_delete=<span class="literal">False</span>)</span><br><span class="line">    pagination_class =MyCursorPagination</span><br></pre></td></tr></table></figure>





<h1 id="四-异常处理-Exceptions"><a href="#四-异常处理-Exceptions" class="headerlink" title="四 异常处理 Exceptions"></a>四 异常处理 Exceptions</h1><p>REST framework提供了异常处理，我们可以自定义异常处理函数。</p>
<h2 id="4-1-使用方式"><a href="#4-1-使用方式" class="headerlink" title="4.1 使用方式"></a>4.1 使用方式</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> rest_framework.views <span class="keyword">import</span> exception_handler</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">custom_exception_handler</span><span class="params">(exc, context)</span>:</span></span><br><span class="line">    <span class="comment"># 先调用REST framework默认的异常处理方法获得标准错误响应对象</span></span><br><span class="line">    response = exception_handler(exc, context)</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 在此处补充自定义的异常处理</span></span><br><span class="line">    <span class="keyword">if</span> response <span class="keyword">is</span> <span class="literal">None</span>:</span><br><span class="line">        response.data[<span class="string">'status_code'</span>] = response.status_code</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> response</span><br></pre></td></tr></table></figure>

<p>在配置文件中声明自定义的异常处理</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">REST_FRAMEWORK = &#123;</span><br><span class="line">    <span class="string">'EXCEPTION_HANDLER'</span>: <span class="string">'my_project.my_app.utils.custom_exception_handler'</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>如果未声明，会采用默认的方式，如下</p>
<p>rest_frame/settings.py</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">REST_FRAMEWORK = &#123;</span><br><span class="line">    <span class="string">'EXCEPTION_HANDLER'</span>: <span class="string">'rest_framework.views.exception_handler'</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="4-2-案例"><a href="#4-2-案例" class="headerlink" title="4.2 案例"></a>4.2 案例</h2><p>补充上处理关于数据库的异常</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> rest_framework.views <span class="keyword">import</span> exception_handler</span><br><span class="line"><span class="keyword">from</span> rest_framework.response <span class="keyword">import</span> Response</span><br><span class="line"><span class="keyword">from</span> rest_framework.views <span class="keyword">import</span> exception_handler <span class="keyword">as</span> drf_exception_handler</span><br><span class="line"><span class="keyword">from</span> rest_framework <span class="keyword">import</span> status</span><br><span class="line"><span class="keyword">from</span> django.db <span class="keyword">import</span> DatabaseError</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">exception_handler</span><span class="params">(exc, context)</span>:</span></span><br><span class="line">    response = drf_exception_handler(exc, context)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> response <span class="keyword">is</span> <span class="literal">None</span>:</span><br><span class="line">        view = context[<span class="string">'view'</span>]</span><br><span class="line">        print(<span class="string">'[%s]: %s'</span> % (view, exc))</span><br><span class="line">        <span class="keyword">if</span> isinstance(exc, DatabaseError):</span><br><span class="line">            response = Response(&#123;<span class="string">'detail'</span>: <span class="string">'服务器内部错误'</span>&#125;, status=status.HTTP_507_INSUFFICIENT_STORAGE)</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            response = Response(&#123;<span class="string">'detail'</span>: <span class="string">'未知错误'</span>&#125;, status=status.HTTP_500_INTERNAL_SERVER_ERROR)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> response</span><br><span class="line">  </span><br><span class="line"><span class="comment"># 在setting.py中配置</span></span><br><span class="line">REST_FRAMEWORK = &#123;</span><br><span class="line">    <span class="string">'EXCEPTION_HANDLER'</span>: <span class="string">'app01.ser.exception_handler'</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="4-3-REST-framework定义的异常"><a href="#4-3-REST-framework定义的异常" class="headerlink" title="4.3 REST framework定义的异常"></a>4.3 REST framework定义的异常</h2><ul>
<li>APIException 所有异常的父类</li>
<li>ParseError 解析错误</li>
<li>AuthenticationFailed 认证失败</li>
<li>NotAuthenticated 尚未认证</li>
<li>PermissionDenied 权限决绝</li>
<li>NotFound 未找到</li>
<li>MethodNotAllowed 请求方式不支持</li>
<li>NotAcceptable 要获取的数据格式不支持</li>
<li>Throttled 超过限流次数</li>
<li>ValidationError 校验失败</li>
</ul>
<p>也就是说，很多的没有在上面列出来的异常，就需要我们在自定义异常中自己处理了。</p>
</section>
    <!-- Tags START -->
    
    <!-- Tags END -->
    <!-- NAV START -->
    
  <div class="nav-container">
    <!-- reverse left and right to put prev and next in a more logic postition -->
    
      <a class="nav-left" href="/python/Django-rest-framework%E6%A1%86%E6%9E%B6/8-drf-%E8%87%AA%E5%8A%A8%E7%94%9F%E6%88%90%E6%8E%A5%E5%8F%A3%E6%96%87%E6%A1%A3/">
        <span class="nav-arrow">← </span>
        
          python/Django-rest-framework框架/8-drf-自动生成接口文档
        
      </a>
    
    
      <a class="nav-right" href="/linux/%E5%85%A5%E9%97%A8%E5%88%B0%E7%B2%BE%E9%80%9A/03-Linux-Shell/">
        
          linux/入门到精通/03-Linux-Shell
        
        <span class="nav-arrow"> →</span>
      </a>
    
  </div>

    <!-- NAV END -->
    <!-- 打赏 START -->
    
      <div class="money-like">
        <div class="reward-btn">
          赏
          <span class="money-code">
            <span class="alipay-code">
              <div class="code-image"></div>
              <b>使用支付宝打赏</b>
            </span>
            <span class="wechat-code">
              <div class="code-image"></div>
              <b>使用微信打赏</b>
            </span>
          </span>
        </div>
        <p class="notice">点击上方按钮,请我喝杯咖啡！</p>
      </div>
    
    <!-- 打赏 END -->
    <!-- 二维码 START -->
    
      <div class="qrcode">
        <canvas id="share-qrcode"></canvas>
        <p class="notice">扫描二维码，分享此文章</p>
      </div>
    
    <!-- 二维码 END -->
    
      <!-- Gitment START -->
      <div id="comments"></div>
      <!-- Gitment END -->
    
  </article>
  <!-- Article END -->
  <!-- Catalog START -->
  
    <aside class="catalog-container">
  <div class="toc-main">
  <!-- 不蒜子统计 -->
    <strong class="toc-title">目录</strong>
    
      <ol class="toc-nav"><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#一-过滤Filtering"><span class="toc-nav-text">一 过滤Filtering</span></a></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#二-排序"><span class="toc-nav-text">二 排序</span></a></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#三-分页Pagination"><span class="toc-nav-text">三 分页Pagination</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#可选分页器"><span class="toc-nav-text">可选分页器</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#应用"><span class="toc-nav-text">应用</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#四-异常处理-Exceptions"><span class="toc-nav-text">四 异常处理 Exceptions</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#4-1-使用方式"><span class="toc-nav-text">4.1 使用方式</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#4-2-案例"><span class="toc-nav-text">4.2 案例</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#4-3-REST-framework定义的异常"><span class="toc-nav-text">4.3 REST framework定义的异常</span></a></li></ol></li></ol>
    
  </div>
</aside>
  
  <!-- Catalog END -->
</main>

<script>
  (function () {
    var url = 'http://www.liuqingzheng.top/python/Django-rest-framework框架/7-drf-过滤排序分页异常处理/';
    var banner = ''
    if (banner !== '' && banner !== 'undefined' && banner !== 'null') {
      $('#article-banner').css({
        'background-image': 'url(' + banner + ')'
      })
    } else {
      $('#article-banner').geopattern(url)
    }
    $('.header').removeClass('fixed-header')

    // error image
    $(".markdown-content img").on('error', function() {
      $(this).attr('src', 'http://file.muyutech.com/error-img.png')
      $(this).css({
        'cursor': 'default'
      })
    })

    // zoom image
    $(".markdown-content img").on('click', function() {
      var src = $(this).attr('src')
      if (src !== 'http://file.muyutech.com/error-img.png') {
        var imageW = $(this).width()
        var imageH = $(this).height()

        var zoom = ($(window).width() * 0.95 / imageW).toFixed(2)
        zoom = zoom < 1 ? 1 : zoom
        zoom = zoom > 2 ? 2 : zoom
        var transY = (($(window).height() - imageH) / 2).toFixed(2)

        $('body').append('<div class="image-view-wrap"><div class="image-view-inner"><img src="'+ src +'" /></div></div>')
        $('.image-view-wrap').addClass('wrap-active')
        $('.image-view-wrap img').css({
          'width': `${imageW}`,
          'transform': `translate3d(0, ${transY}px, 0) scale3d(${zoom}, ${zoom}, 1)`
        })
        $('html').css('overflow', 'hidden')

        $('.image-view-wrap').on('click', function() {
          $(this).remove()
          $('html').attr('style', '')
        })
      }
    })
  })();
</script>


  <script>
    var qr = new QRious({
      element: document.getElementById('share-qrcode'),
      value: document.location.href
    });
  </script>



  <script>
    var gitmentConfig = "liuqingzheng";
    if (gitmentConfig !== 'undefined') {
      var gitment = new Gitment({
        id: "python/Django-rest-framework框架/7-drf-过滤排序分页异常处理",
        owner: "liuqingzheng",
        repo: "FuckBlog",
        oauth: {
          client_id: "32a4076431cf39d0ecea",
          client_secret: "94484bd79b3346a949acb2fda3c8a76ce16990c6"
        },
        theme: {
          render(state, instance) {
            const container = document.createElement('div')
            container.lang = "en-US"
            container.className = 'gitment-container gitment-root-container'
            container.appendChild(instance.renderHeader(state, instance))
            container.appendChild(instance.renderEditor(state, instance))
            container.appendChild(instance.renderComments(state, instance))
            container.appendChild(instance.renderFooter(state, instance))
            return container;
          }
        }
      })
      gitment.render(document.getElementById('comments'))
    }
  </script>




    <div class="scroll-top">
  <span class="arrow-icon"></span>
</div>
    <footer class="app-footer">
<!-- 不蒜子统计 -->
<span id="busuanzi_container_site_pv">
     本站总访问量<span id="busuanzi_value_site_pv"></span>次
</span>
<span class="post-meta-divider">|</span>
<span id="busuanzi_container_site_uv" style='display:none'>
     本站访客数<span id="busuanzi_value_site_uv"></span>人
</span>
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>



  <p class="copyright">
    &copy; 2021 | Proudly powered by <a href="https://www.cnblogs.com/xiaoyuanqujing" target="_blank">小猿取经</a>
    <br>
    Theme by <a href="https://www.cnblogs.com/xiaoyuanqujing" target="_blank" rel="noopener">小猿取经</a>
  </p>
</footer>

<script>
  function async(u, c) {
    var d = document, t = 'script',
      o = d.createElement(t),
      s = d.getElementsByTagName(t)[0];
    o.src = u;
    if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
    s.parentNode.insertBefore(o, s);
  }
</script>
<script>
  async("//cdnjs.cloudflare.com/ajax/libs/fastclick/1.0.6/fastclick.min.js", function(){
    FastClick.attach(document.body);
  })
</script>

<script>
  var hasLine = 'true';
  async("//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js", function(){
    $('figure pre').each(function(i, block) {
      var figure = $(this).parents('figure');
      if (hasLine === 'false') {
        figure.find('.gutter').hide();
      }
      var lang = figure.attr('class').split(' ')[1] || 'code';
      var codeHtml = $(this).html();
      var codeTag = document.createElement('code');
      codeTag.className = lang;
      codeTag.innerHTML = codeHtml;
      $(this).attr('class', '').empty().html(codeTag);
      figure.attr('data-lang', lang.toUpperCase());
      hljs.highlightBlock(block);
    });
  })
</script>





<!-- Baidu Tongji -->

<script>
    var _baId = 'c5fd96eee1193585be191f318c3fa725';
    // Originial
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?" + _baId;
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
</script>


<script src="/js/script.js"></script>


<script src="/js/search.js"></script>


<script src="/js/load.js"></script>



  <span class="local-search local-search-google local-search-plugin" style="right: 50px;top: 70px;;position:absolute;z-index:2;">
      <input type="search" placeholder="站内搜索" id="local-search-input" class="local-search-input-cls" style="">
      <div id="local-search-result" class="local-search-result-cls"></div>
  </span>


  </body>
</html>